<?php

namespace app\controller;

use support\Request;
use Kingbes\Attribute\Annotation;
use Webman\Captcha\CaptchaBuilder;
use app\common\Tool;

#[Annotation(title: "插件组")]
class InstallController
{
    #[Annotation(title: "安装")]
    public function index(Request $request)
    {
        if ($request->method() === "POST") {
            $database_config_file = base_path() . '/config/database.php';
            clearstatcache();
            if (is_file($database_config_file)) {
                return error('管理后台已经安装！如需重新安装，请删除该插件数据库配置文件并重启');
            }
            if (!class_exists(CaptchaBuilder::class)) {
                return error('请先restart重启webman后再进行此页面的设置');
            }

            // 数据库
            $user = $request->post("user");
            $password = $request->post('password');
            $database = $request->post('database');
            $host = $request->post('host');
            $port = (int)$request->post('port') ?: 3306;
            $time = time();
            try {
                $db = Tool::getPdo($host, $user, $password, $port);
                $smt = $db->query("show databases like '$database'");
                if (empty($smt->fetchAll())) {
                    $db->exec("create database $database");
                }
                $db->exec("use $database");

                // 安装
                $sql_file = base_path() . '/install.sql';
                if (!is_file($sql_file)) {
                    return error('数据库SQL文件不存在');
                }
                $sql_file = file_get_contents($sql_file);
                $sql_file = Tool::removeComments($sql_file);

                $res_sql = $db->exec($sql_file);
                $db->exec("INSERT INTO `kb_admin_roles` VALUES (1, 0, '超级管理员', 'all', $time, $time);
                INSERT INTO `kb_menu` VALUES (1, 0, '网站配置', 'layui-icon-set', '', '目录', '', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (2, 3, '菜单管理', '', 'admin.menu.query', '菜单', '_iframe', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (3, 0, '权限管理', 'layui-icon-auz', '', '目录', '', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (4, 3, '账号管理', '', 'admin.admin.query', '菜单', '_iframe', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (5, 3, '角色管理', '', 'admin.adminRoles.query', '菜单', '_iframe', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (7, 1, '附件管理', '', 'admin.attachment.query', '菜单', '_iframe', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (8, 1, '系统设置', '', 'admin.config.systems', '菜单', '_iframe', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (9, 2, '新增', '', 'admin.menu.add', '权限', '', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (10, 2, '编辑', '', 'admin.admin.edit', '权限', '', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (11, 2, '删除', '', 'admin.admin.del', '权限', '', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (12, 7, '编辑', '', 'admin.attachment.edit', '权限', '', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (13, 7, '删除', '', 'admin.attachment.del', '权限', '', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (14, 4, '新增', '', 'admin.admin.add', '权限', '', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (15, 4, '编辑', '', 'admin.admin.edit', '权限', '', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (16, 4, '删除', '', 'admin.admin.del', '权限', '', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (17, 5, '新增', '', 'admin.adminRoles.add', '权限', '', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (18, 5, '编辑', '', 'admin.adminRoles.edit', '权限', '', 0, $time, $time);
                INSERT INTO `kb_menu` VALUES (19, 5, '删除', '', 'admin.adminRoles.del', '权限', '', 0, $time, $time);
                INSERT INTO `kb_options` VALUES (1, 'logo', '{\"title\":\"KingBes Admin\",\"image\":\"/assets/images/logo.png\"}', $time, $time);");
            } catch (\Throwable $e) {
                if (stripos($e, 'Access denied for user')) {
                    return error('数据库用户名或密码错误');
                }
                if (stripos($e, 'Connection refused')) {
                    return error('Connection refused. 请确认数据库IP端口是否正确，数据库已经启动');
                }
                if (stripos($e, 'timed out')) {
                    return error('数据库连接超时，请确认数据库IP端口是否正确，安全组及防火墙已经放行端口');
                }
                return error(msg: "错误信息！", data: $e);
            }

            // 后台账号
            $adminuser = $request->post("adminuser");
            $adminpwd = $request->post("adminpwd");
            $adminpwd_confirm = $request->post("adminpwd_confirm");
            // 验证
            if ($adminpwd != $adminpwd_confirm) {
                return error(msg: '两次密码不一致', data: "adminpwd_confirm");
            }
            if ($res_sql !== false) {
                $smt = $db->prepare("insert into `kb_admins` (`username`, `password`,`nickname`, `rid`, `create_time`, `update_time`) values (:username, :password, :nickname, :rid, :create_time, :update_time)");
                $time = time();
                $data = [
                    'username' => $adminuser,
                    'password' => password_hash($adminpwd, PASSWORD_DEFAULT),
                    'nickname' => '超级管理员',
                    'rid' => 1,
                    'create_time' => $time,
                    'update_time' => $time
                ];
                foreach ($data as $key => $value) {
                    $smt->bindValue($key, $value);
                }
                $smt->execute();

                $config_content = <<<EOF
<?php
return  [
    'default' => 'mysql',
    'connections' => [
        'mysql' => [
            'driver'      => 'mysql',
            'host'        => '$host',
            'port'        => '$port',
            'database'    => '$database',
            'username'    => '$user',
            'password'    => '$password',
            'charset'     => 'utf8mb4',
            'collation'   => 'utf8mb4_general_ci',
            'prefix'      => '',
            'strict'      => true,
            'engine'      => null,
        ],
    ],
];
EOF;

                file_put_contents($database_config_file, $config_content);

                $think_orm_config = <<<EOF
<?php
return [
    'default' => 'mysql',
    'connections' => [
        'mysql' => [
            // 数据库类型
            'type' => 'mysql',
            // 服务器地址
            'hostname' => '$host',
            // 数据库名
            'database' => '$database',
            // 数据库用户名
            'username' => '$user',
            // 数据库密码
            'password' => '$password',
            // 数据库连接端口
            'hostport' => $port,
            // 数据库连接参数
            'params' => [
                // 连接超时3秒
                \PDO::ATTR_TIMEOUT => 3,
            ],
            // 数据库编码默认采用utf8
            'charset' => 'utf8mb4',
            // 数据库表前缀
            'prefix' => 'kb_',
            // 断线重连
            'break_reconnect' => true,
            // 关闭SQL监听日志
            'trigger_sql' => true,
            // 自定义分页类
            'bootstrap' =>  ''
        ],
    ],
];
EOF;
                $thinkorm_file = base_path() . '/config/thinkorm.php';
                // 检查文件是否存在且可读  
                if (file_exists($thinkorm_file)) {
                    if (is_readable($thinkorm_file)) {
                        $file = fopen($thinkorm_file, 'r+');
                        if ($file) {
                            $modifiedContent = $think_orm_config;
                            fwrite($file, $modifiedContent);
                            fclose($file);
                        }
                    }
                } else {
                    return error("config/thinkorm.php文件没有足够的权限。");
                }
                // 尝试reload
                if (function_exists('posix_kill')) {
                    set_error_handler(function () {
                    });
                    posix_kill(posix_getppid(), SIGUSR1);
                    restore_error_handler();
                }
                return success('安装成功');
            } else {
                return error('安装失败');
            }
        }
        return fetch();
    }
}
